package com.triones.biz.infra.service.ocr;

import cn.hutool.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 百度 ocr 图片文字识别服务
 *
 * @Author: triones
 */
public class BaiduOcrAuthServe {

    /**
     * 百度云应用的AK
     */
//    public static String API_KEY = "qelMB7tjXfma2fTMyRpi8PWm";
    public static String API_KEY = "qelMB7tjXfma2fTMyRpi8PWm";
//    public static String API_KEY = "";

    /**
     * 百度云应用的AS
     */
    public static String API_SECURET_KEY = "wRebGqFVwIPkxmnwp2cMkpDciYluL8kK";
//    public static String API_SECURET_KEY = "";

    /**
     * 获取token地址
     */
    public static String AUTH_HOST = "https://aip.baidubce.com/oauth/2.0/token?";


    /**
     * 获取api访问token
     * @return assess_token
     */
    public static String getAuth() {
        String getAccessTokenUrl = AUTH_HOST
            // 1. grant_type为固定参数
            + "grant_type=client_credentials"
            // 2. 官网获取的 API Key
            + "&client_id=" + API_KEY
            // 3. 官网获取的 Secret Key
            + "&client_secret=" + API_SECURET_KEY;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.get("access_token").toString();
            return access_token;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

    /**
     * 获取 AssessToken 值
     * @return
     */
    public String getAssessToken() {



        return null;
    }

    public static void main(String[] args) {
        String auth = getAuth();
    }
}
